﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Activation;
using System.ServiceModel;
using System.IO;
using COFE.Core;
using COFE.Core.Utils;
using COFE.Core.EntryType;
using System.ServiceModel.Web;
using System.Net;
using System.Globalization;

namespace COFE.Web.Services
{

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class EntryTypeServices : IEntryTypeServices
    {
        #region Constructor

        #endregion

        #region Methods

        public Stream GetEntryType(string typeID, string rel, string json)
        {
            return ServicesUtils.ExecuteAndReturn<string, Stream>(
                 (tID) =>
                 {
                     var entryType = COFEShared.EntryTypeDictionary[new Guid(tID)];
                     if (entryType == null)
                         throw new KeyNotFoundException(tID);
                     if (!String.IsNullOrEmpty(rel))
                     {
                         var link = new EntryType(entryType).CreateLinks().FirstOrDefault(
                             l => l.RelationString.Equals(rel, StringComparison.InvariantCultureIgnoreCase));
                         if (link != null)
                         {
                             ServicesUtils.SetRedirect(link.Uri, true, "rel");
                             return null;
                         }
                         throw new KeyNotFoundException(rel);
                     }

                     return EncodeObjectUtils.EncodeObject(new EntryType(entryType), json);
                 }, typeID);
        }

        public Stream GetIcon(string typeID, string size)
        {
            return ServicesUtils.ExecuteAndReturn<string, Stream>(
                  (tID) =>
                  {
                      if (string.IsNullOrEmpty(size))
                          size = IconProperties.SmallIcon.ToString();
                      size = size.ToLower();
                      if (!size.EndsWith("icon"))
                          size += "icon";

                      IconProperties iconProp;
                      if (!(EnumUtils<IconProperties>.EnumTryParse(size, out iconProp)))
                          throw new KeyNotFoundException("size");

                      var entryType = COFEShared.EntryTypeDictionary[new Guid(tID)];
                      if (entryType == null)
                          throw new KeyNotFoundException(tID);

                      Stream ms = new MemoryStream();                      
                      entryType.GetIcon(iconProp).SaveAsPNGStream(ms);
                      ms.Seek(0, SeekOrigin.Begin);
                      ServicesUtils.SetContentHeaderAsFile(String.Format("[{0}]{1}.png", size, typeID));
                      //http://stackoverflow.com/questions/8406377/http-response-header-format-for-expires
                      WebOperationContext.Current.OutgoingResponse.Headers.Add(
                          HttpResponseHeader.Expires, DateTime.Now.AddDays(30).ToUniversalTime()
                            .ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture));
                      return ms;
                  }, typeID);
        }

        #endregion

        #region Data

        #endregion

        #region Public Propertiers

        #endregion


    }
}